package net.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 	聊天室客户端类
 * @author Administrator
 *
 */
public class Client {
	
	private Socket socket;
	
	public Client(String address, int port) throws IOException {
		System.out.println("客户端正在链接");
		socket = new Socket(address, port);
		System.out.println("客户端已连接");
	}
	
	/**
	 * 	客户端启用
	 * @throws IOException 
	 */
	public void start() throws IOException {
		
		// 接收服务器发送过来的数据
		new Thread() {
			public void run() {
				try {
					InputStream in = socket.getInputStream();
					byte[] content = new byte[1024];
					int length = in.read(content);
					while(length != -1) {
						// 输出读到的内容
						System.out.println(new String(content, 0, length));
						// 循环读
						length = in.read(content);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			};
		}.start();
		
		// 往服务器写东西
		Scanner scanner = new Scanner(System.in);
		OutputStream out = socket.getOutputStream();
		while(true) {
			String content = scanner.nextLine();
			out.write(content.getBytes());
		}
//		scanner.close();
	}
	
}
